package com.zjw.javase.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;

import com.zjw.javase.reflect.model.Person;

/**
 * 反射测试
 * @author zjw
 *
 */
public class TestReflect {

	/**
	 * 测试Class对象的三种创建方式
	 */
	@Test
	public void testRef01() throws ClassNotFoundException {
		Class clazz1 = new Person().getClass(); // 1.Objec.getClass();

		String className = "com.zjw.javase.reflect.model.Person";
		Class clazz2 = Class.forName(className); // 2.Class.forName()

		Class clazz3 = Person.class; // 3.xxx.class

		System.out.println(clazz1);
		// there is one class in mem
		System.out.println(clazz1 == clazz2);// true
		System.out.println(clazz1 == clazz3);// true

	}
	
	/**
	 *测试通过反射来创建对象 
	 * @throws Exception 
	 */
	@Test
	public void testRef02() throws Exception {

		Class<Person> personClass = Person.class;

		Person p1 = personClass.newInstance();// p1 = new Person();
		System.out.println(p1);

		Constructor[] cs = personClass.getConstructors();// get all constructors
		for (Constructor c : cs) {
			System.out.println(c);
		}

		Constructor constructor = personClass.getConstructor(String.class,
				char.class, int.class);
		p1 = (Person) constructor.newInstance("zjw", '男', 20);// p1 = new Person(xx,xx,xx);
		System.out.println(p1);

	}
	
	/**
	 * Class类的常用方法测试
	 */
	@Test
	public void testRef03() {
		Class personClass = Person.class;

		System.out.println(personClass.getName());// com.zjw.javase.reflect.model.Person
		Package _package = personClass.getPackage();
		System.out.println(_package);// package com.zjw.javase.reflect.model

		Method[] methods = personClass.getMethods();// all public methods
													// contains parent's method
		methods = personClass.getDeclaredMethods();// all methods contains
													// private methods but don't
													// have parent's methods
		for (Method method : methods) {
			System.out.println("methodName: " + method.getName());
			int modifiers = method.getModifiers();
			System.out.println("modifiers: " + modifiers + " , " + Modifier.toString(modifiers));
			System.out.println("----------------------");
		}
		
		Field[] fields = personClass.getFields();//fields
//		fields = personClass.getDeclaredFields();
		for(Field field:fields){
			System.out.println(field.getName());
		}

	}
	
	/**
	 * 通过Class调用类中的方法和属性
	 * @throws SecurityException 
	 * @throws Exception 
	 */
	@Test
	public void testRef04() throws Exception {
		Class personClass = Person.class;
		
		Method method = personClass.getDeclaredMethod("sayHello", String.class);
		method.setAccessible(true);
		method.invoke(new Person(), "zjw");
		
		Field field = personClass.getDeclaredField("name");
		field.setAccessible(true);
		Person p = new Person("laowu",'男',18);
		System.out.println("name is: "  + field.get(p));
		field.set(p, "laoliu");
		System.out.println(p.getName());
	}
}













